package scau.zhong.controller;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import scau.zhong.common.exception.ErrorInfo;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.file.AccessDeniedException;

@ControllerAdvice
public class UserServiceException {
//    @ExceptionHandler(scau.zhong.common.user.UserServiceException.class)
//    @ResponseBody
//    public ErrorInfo<String> handleException(HttpServletRequest request, scau.zhong.common.user.UserServiceException e){
//        ErrorInfo<String> errorInfo = new ErrorInfo<>();
//        errorInfo.setMessage(e.getMessage());
//        errorInfo.setUrl(request.getRequestURI());
//        errorInfo.setCode(ErrorInfo.ERROR);
//        errorInfo.setData("服务异常，请联系管理员");
//        return errorInfo;
//    }

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ErrorInfo<String> handleException(HttpServletRequest request,Exception e){
        if(e instanceof AccessDeniedException){
            ErrorInfo<String> errorInfo = new ErrorInfo<>();
            errorInfo.setMessage(e.getMessage());
            errorInfo.setStatus(HttpServletResponse.SC_FORBIDDEN);
            errorInfo.setData("权限不足，无法访问");
            return errorInfo;
        }
        if(e instanceof scau.zhong.common.user.UserServiceException){
            ErrorInfo<String> errorInfo = new ErrorInfo<>();
            errorInfo.setMessage(e.getMessage());
            errorInfo.setUrl(request.getRequestURI());
            errorInfo.setStatus(ErrorInfo.ERROR);
            errorInfo.setData("服务异常，请联系管理员");
            return errorInfo;
        }

        ErrorInfo<String> errorInfo = new ErrorInfo<>();
        errorInfo.setMessage(e.getMessage());
        errorInfo.setUrl(request.getRequestURI());
        errorInfo.setStatus(500);
        errorInfo.setData("服务器内部错误");
        return errorInfo;
    }
}
